package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 类描述：
 */
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ?") //每分钟执行一次
    public void processTimeoutOrder() {
        //查询超时订单
        //select * from orders where status = 待付款 and order_time < 当前时间-15分钟
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> timeoutOrderList=orderMapper.getOrdersByStatusAndOrdertime(status,time);
        if (timeoutOrderList != null && timeoutOrderList.size() > 0) {
            for (Orders orders : timeoutOrderList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点执行一次
    public void processCompletedOrder() {
        //查询派送中的订单
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);
        List<Orders> timeoutOrderList=orderMapper.getOrdersByStatusAndOrdertime(status,time);
        if (timeoutOrderList != null && timeoutOrderList.size() > 0) {
            for (Orders orders : timeoutOrderList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
